/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.plan.service;

import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.plan.dao.MaterialRequisiteFormDAO;
import com.javaeye.plan.dto.MaterialRequisiteForm;
import com.javaeye.plan.dto.MaterialRequisiteFormDetail;
import com.javaeye.plan.web.VoucherCondition;
import com.javaeye.store.dao.MaterialsBatchDetailDAO;
import com.javaeye.store.dao.MaterialsChangeDetailDAO;
import com.javaeye.store.dao.MaterialsSKUDetailDAO;
import com.javaeye.store.dto.MaterialsBatchDetail;
import com.javaeye.store.dto.MaterialsChangeDetail;
import com.javaeye.store.dto.MaterialsSKUDetail;
import com.javaeye.common.util.DateUtils;
import com.javaeye.common.util.ListUtil;
import com.javaeye.common.web.PageInfo;
import com.javaeye.delivery.dao.OrderDetailBatchInfoDAO;
import com.javaeye.delivery.dto.OrderDetailBatchInfo;

public class MaterialRequisiteFormService implements IMaterialRequisiteFormService {
	
	private static Log log = LogFactory.getLog(MaterialRequisiteFormService.class);
	
	private MaterialRequisiteFormDAO dao;
	
	private MaterialsChangeDetailDAO materialsChangeDetailDao;
	
	private MaterialsBatchDetailDAO materialsBatchDetailDao;
	
	private OrderDetailBatchInfoDAO orderDetailBatchInfoDao;
	
	private MaterialsSKUDetailDAO materialsSKUDetailDao;
	
	public void setDao(MaterialRequisiteFormDAO dao) {
		this.dao = dao;
	}
	
	public void setOrderDetailBatchInfoDao(
			OrderDetailBatchInfoDAO orderDetailBatchInfoDao) {
		this.orderDetailBatchInfoDao = orderDetailBatchInfoDao;
	}
	
	public void setMaterialsChangeDetailDao(
			MaterialsChangeDetailDAO materialsChangeDetailDao) {
		this.materialsChangeDetailDao = materialsChangeDetailDao;
	}

	public void setMaterialsSKUDetailDao(MaterialsSKUDetailDAO materialsSKUDetailDao) {
		this.materialsSKUDetailDao = materialsSKUDetailDao;
	}

	public void setMaterialsBatchDetailDao(
			MaterialsBatchDetailDAO materialsBatchDetailDao) {
		this.materialsBatchDetailDao = materialsBatchDetailDao;
	}

	@SuppressWarnings("unchecked")
	public List<MaterialRequisiteForm> getFormList(VoucherCondition condition, PageInfo pageInfo) {
		List result = dao.getPageData(condition, pageInfo);
		if (result == null || result.size() == 0) {
			log.warn("数据库中未找到指定的领料单信息");
		}
		return result;
	}

	public MaterialRequisiteForm getMaterialRequisiteForm(String formId) {
		MaterialRequisiteForm form = dao.getMaterialRequisiteForm(formId);
		if (form == null) {
			log.warn("数据库中未找到指定的领料单信息，单号：" + formId);
			return new MaterialRequisiteForm();
		}
		return form;
	}
	
	public void removeMaterialRequisiteForm(String formId) {
		MaterialRequisiteForm form = dao.getMaterialRequisiteForm(formId);
		Set<MaterialRequisiteFormDetail> details = form.getFormDetails();
		for (MaterialRequisiteFormDetail detail : details) {
			List<OrderDetailBatchInfo> batchInfos = 
				orderDetailBatchInfoDao.getBatchInfo(formId, detail.getMaterialId());
			//log.warn("delete orderId=" + formId + ", MaterialId=" + detail.getMaterialId() + ",count=" + batchInfos.size());
			for (OrderDetailBatchInfo batchInfo : batchInfos) {
				orderDetailBatchInfoDao.removeOrderDetailBatchInfo(batchInfo.getId());
			}
		}
		dao.removeMaterialRequisiteForm(formId);
	}
	
	public void saveMaterialRequisiteForm(MaterialRequisiteForm form) {
		int type = form.getType();
		if (null == form.getId() || "".equals(form.getId())) {
			String id = ListUtil.MATERIALS_REQUISITE_ORDER_ID_PRE + DateUtils.dateToString("yyyyMM");
			int maxId = dao.getMaxMaterialRequisiteFormId(id) + 1;
			id = id + String.format("%04d", maxId);
			log.debug("生成的领料单编号：" + id);
			//生成领料单ID
			form.setId(id);
			//特殊退料单
			if (type == MaterialRequisiteForm.FORM_TYPE_QUALIFIED_BACK
				|| type == MaterialRequisiteForm.FORM_TYPE_UNQUALIFIED_BACK) {
				form.setSourceFormId(id);
			}
			form.setStatus(MaterialRequisiteForm.MATERIAL_REQUISITE_FORM_STATUS_CREATE);
		}
		dao.saveMaterialRequisiteForm(form);
		//特殊退料单
		if (type == MaterialRequisiteForm.FORM_TYPE_QUALIFIED_BACK
				|| type == MaterialRequisiteForm.FORM_TYPE_UNQUALIFIED_BACK) {
			Set<MaterialRequisiteFormDetail> details = form.getFormDetails();
			for (MaterialRequisiteFormDetail detail : details) {
				//生成领料单出库明细
				OrderDetailBatchInfo batchInfo = new OrderDetailBatchInfo();
				batchInfo.setOrderId(form.getSourceFormId());
				batchInfo.setOrderDetailId(detail.getId());
				batchInfo.setProductId(detail.getMaterialId());
				batchInfo.setBatchNo("A201110");
				batchInfo.setNumber(detail.getNumber());
				orderDetailBatchInfoDao.save(batchInfo);
			}
		}
	}
	
	public void materialRequisiteFormOutStore(String formId, List<OrderDetailBatchInfo> batchInfos) {
		MaterialRequisiteForm form = getMaterialRequisiteForm(formId);
		form.setStatus(MaterialRequisiteForm.MATERIAL_REQUISITE_FORM_STATUS_FINISH);
		
		Set<MaterialRequisiteFormDetail> details = form.getFormDetails();
		for (MaterialRequisiteFormDetail detail : details) {
			detail.setRealNumber(getOutStoreNumber(detail.getMaterialId(), batchInfos));
		}
		dao.saveMaterialRequisiteForm(form);
		
		for (OrderDetailBatchInfo batchInfo : batchInfos) {
			//保存领料单出库明细
			orderDetailBatchInfoDao.save(batchInfo);
			
			int materialsId = batchInfo.getProductId();
			//插入库存变动明细表
			MaterialsChangeDetail changeDetail = new MaterialsChangeDetail();
			changeDetail.setMaterialsId(materialsId);
			changeDetail.setVoucherNo(formId);
			changeDetail.setChangeType(MaterialsChangeDetail.MATERIALS_OUTSTORE);
			changeDetail.setBatchNo(batchInfo.getBatchNo());
			changeDetail.setNumber(batchInfo.getNumber());
			materialsChangeDetailDao.save(changeDetail);
			
			//更新实时库存数量
			MaterialsSKUDetail skuDetail = materialsSKUDetailDao.getMaterialsSKUDetail(materialsId);
			skuDetail.setNumber(skuDetail.getNumber() - batchInfo.getNumber());
			materialsSKUDetailDao.saveMaterialsSKUDetail(skuDetail);
			
			//更新批次库存数量
			MaterialsBatchDetail batchDetail = 
				materialsBatchDetailDao.getBatchDetail(materialsId, batchInfo.getBatchNo());
			batchDetail.setOutNumber(batchDetail.getOutNumber() + batchInfo.getNumber());
			materialsBatchDetailDao.save(batchDetail);
		}
	}
	
	private float getOutStoreNumber(int materialId, List<OrderDetailBatchInfo> batchInfos) {
		float totle = 0;
		for (OrderDetailBatchInfo info : batchInfos) {
			if (info.getProductId() == materialId) {
				totle += info.getNumber();
			}
		}
		return totle;
	}
}
